package com.zhu.exception;

import com.zhu.config.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Date;

/**
 * @author zhl
 * @date 2020/09/25
 */

@Slf4j
@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = AppRuntimeException.class)
    @ResponseBody
    public Result orderRuntimeExceptionHandler(AppRuntimeException e) {
        log.warn("[{}]于[{}] {}","用户", new Date(), e.getMessage());
        if (e.getCode() != null) {
            return new Result<>().fail(e.getCode(), e.getMessage());
        }
        if (e.getMessage() != null) {
            return new Result<>().fail(e.getCode(), e.getMessage());
        }
        return new Result<>().fail("E500", "系统异常");
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        return this.bindingResultHandler(e, bindingResult);
    }

    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Result bindExceptionHandler(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        return this.bindingResultHandler(e, bindingResult);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result methodExceptionHandler(Exception e) {
        log.error("系统异常{}", e);
        return new Result<>().fail("E500", "系统异常");
    }

    private Result bindingResultHandler(Exception e, BindingResult bindingResult) {
        String errorDefaultMessage = bindingResult.getAllErrors().get(0).getDefaultMessage();
        String msgByCode = "";

        String errorCode;
        String errorMessage;

        if (StringUtils.isNotBlank(msgByCode)) {
            errorCode = errorDefaultMessage;
            errorMessage = msgByCode;
        } else {
            errorCode = "";
            errorMessage = errorDefaultMessage;
        }

        log.warn("[[{}] {}", new Date(), e.getMessage());

        return new Result<>().fail(errorCode, errorMessage);
    }
}
